#!/bin/sh

#  The logging routine
Log() {
	logger -p install.info -t 'Parallels Installer' "$@"
}

CheckProcessRunning()
{
	Log "Calling CheckProcessRunning"
	process=`ps -w -w -A -ocommand 2>/dev/null | grep "${1}" | grep -v 'grep'`
	if [ $? -eq 0 ]; then
		Log "Process found: ${process}"
		return 0
	fi

	return 1
}

# Wait till dispatcher started.
WaitDispatcherStart() {
	# Wait for Dispatcher to start
	COUNTER=21
	cmd="CheckProcessRunning prl_disp_service"
	if [ "x$1" == "xsocket" ]; then
		cmd="netstat -an | grep -q prl_disp_service.socket"
	fi
	while [ $COUNTER -gt 1 ]; do
		if eval $cmd; then
			Log "Dispatcher $1 is up and running"
			break
		fi
		sleep 1
		let COUNTER-=1
	done
}

#  This is a workaround for tmp dir issue
#  Unset environ TMPDIR
TMPDIR_env="${TMPDIR}"
unset TMPDIR

Log 'Starting service'

# To get rid of unwanted message about
# "New Unconfigured Adapters Have Appeared",
# block UserNotification center until dispatcher is started.

launchctl unload /System/Library/LaunchDaemons/com.apple.UserNotificationCenter.plist

launchctl load /Library/LaunchDaemons/com.parallels.desktop.launchdaemon.plist
launchctl start com.parallels.desktop.launchdaemon

#  Restore environ TMPDIR
TMPDIR="${TMPDIR_env}"
export TMPDIR

WaitDispatcherStart

# Load UserNotificationCenter launchd back again.
launchctl load /System/Library/LaunchDaemons/com.apple.UserNotificationCenter.plist

"/Library/Parallels/Parallels Service.app/Contents/Resources/ParallelsDispatcherService" ext-load

# PD5 GUI listen local host interfaces
# PD6 Dispatcher listen only local sockets
# Ask PD6 Dispatcher listen local host interface
# to avoid broken connect of PD6 Dispatcher and PD5 GUI
# Bug #484389
# Wait dispatcher socket up and running
WaitDispatcherStart socket
Log "Ask dispatcher to listen local host network interface"
prlsrvctl up-listen-interface --listen-interface A40B1FAE-EBF5-4FA7-A748-40388FCFF47D

# Copy receipts to Parallels Receipts directory
SWD=`cd "${0%/*}"; pwd`
. "${SWD}"/receipt.sh

# Just to finish installation with good mood
true
